<template>
  <div id="userManagePage" class="page-container">
    <!-- 搜索表单卡片 -->
    <a-card class="search-card">
      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="账号">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="输入账号"
            allow-clear
            class="search-input"
          />
        </a-form-item>
        <a-form-item label="用户名">
          <a-input
            v-model:value="searchParams.userName"
            placeholder="输入用户名"
            allow-clear
            class="search-input"
          />
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            class="search-button"
          >
            <search-outlined class="search-icon" />
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 表格卡片 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTableChange"
        class="user-table"
        rowKey="id"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'userAvatar'">
            <div class="avatar-container">
              <a-image
                :src="record.userAvatar || defaultAvatar"
                :width="40"
                class="user-avatar"
                placeholder
              />
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'userRole'">
            <a-tag
              :color="record.userRole === 'admin' ? 'green' : 'blue'"
              class="role-tag"
            >
              {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-popconfirm
              title="确定要删除该用户吗？"
              @confirm="doDelete(record.id)"
              ok-text="是"
              cancel-text="否"
            >
              <a-button
                danger
                class="delete-button"
                icon="delete"
              >
                删除
              </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message, Popconfirm } from 'ant-design-vue'
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { deleteUserUsingPost, listUserVoByPageUsingPost } from '@/api/userController.ts'
import dayjs from 'dayjs'

// 默认头像
const defaultAvatar = 'https://picsum.photos/id/1005/200/200'

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
    sorter: true,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    sorter: true,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    sorter: true,
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    width: 100,
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    sorter: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
  },
]

// 删除用户
const doDelete = async (id: number) => {
  try {
    const res = await deleteUserUsingPost({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      await fetchData()
    } else {
      message.error('删除失败: ' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    message.error('操作失败，请重试')
  }
}

// 数据
const dataList = ref<API.UserVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPageUsingPost({
      ...searchParams,
    })
    if (res.data.data) {
      dataList.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败，' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    message.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 表格变化之后，重新获取数据
const doTableChange = (pagination: any, filters: any, sorter: any) => {
  searchParams.current = pagination.current
  searchParams.pageSize = pagination.pageSize

  // 处理排序
  if (sorter.field) {
    searchParams.sortField = sorter.field
    searchParams.sortOrder = sorter.order === 'ascend' ? 'ascend' : 'descend'
  }

  fetchData()
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
  }
})

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 全局样式变量 */
:root {
  --primary-color: #1890ff;
  --primary-light: #e6f7ff;
  --primary-dark: #096dd9;
  --danger-color: #ff4d4f;
  --danger-light: #fff2f0;
  --success-color: #52c41a;
  --warning-color: #faad14;
  --text-primary: #1f2329;
  --text-secondary: #6b7280;
  --text-tertiary: #9ca3af;
  --bg-light: #f9fafb;
  --border-color: #e5e7eb;
  --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.05);
  --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.07);
  --transition-normal: all 0.3s ease;
}

.page-container {
  background-color: var(--bg-light);
  min-height: 100vh;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}


/* 搜索卡片样式 */
.search-card {
  margin-bottom: 8px;
  border-radius: 8px;
  box-shadow: var(--shadow-sm);
  transition: var(--transition-normal);
  overflow: hidden;
  border: none;
  animation: fadeIn 0.5s ease-out 0.1s both;
}

.search-card:hover {
  box-shadow: var(--shadow-md);
}

.search-form {

  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-input {
  width: 200px;
  transition: var(--transition-normal);
}

.search-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-button {
  transition: var(--transition-normal);
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.search-icon {
  font-size: 16px;
}

/* 表格卡片样式 */
.table-card {
  border-radius: 8px;
  box-shadow: var(--shadow-sm);
  transition: var(--transition-normal);
  border: none;
  animation: fadeIn 0.5s ease-out 0.2s both;
}

.table-card:hover {
  box-shadow: var(--shadow-md);
}

/* 用户表格样式 */
.user-table {
  background-color: #fff;
}

.ant-table-thead > tr > th {
  background-color: var(--bg-light);
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-color);
  transition: var(--transition-normal);
}

.ant-table-thead > tr > th:hover {
  background-color: var(--primary-light);
}

.ant-table-tbody > tr {
  transition: var(--transition-normal);
}

.ant-table-tbody > tr:hover {
  background-color: var(--primary-light);
  transform: translateX(4px);
}

.ant-table-tbody > tr > td {
  border-bottom: 1px solid var(--border-color);
  transition: var(--transition-normal);
}

/* 头像样式 */
.avatar-container {
  padding: 4px 0;
}

.user-avatar {
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: var(--transition-normal);
}

.user-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
}

/* 角色标签样式 */
.role-tag {
  transition: var(--transition-normal);
}

.role-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 删除按钮样式 */
.delete-button {
  transition: var(--transition-normal);
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.delete-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
}



.ant-pagination-item-active a {
  color: #fff;
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-input {
    width: 100%;
  }

  .ant-table-thead > tr > th {
    padding: 8px 4px;
  }

  .ant-table-tbody > tr > td {
    padding: 8px 4px;
  }
}
</style>
